package com.site.util;

import java.lang.reflect.InvocationTargetException;

import com.site.exception.GenericException;

public class ExceptionUtil {


	/**
	 * 将checked exception转换为unchecked exception.
	 * 这个方法通常用于service层捕捉checked异常而转换，进而触发回滚
	 */
	public static RuntimeException convertCheckedExceptionToUnchecked(Exception e) {
		if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
				|| e instanceof NoSuchMethodException)
			return new IllegalArgumentException("Reflection Exception.", e);
		else if (e instanceof InvocationTargetException) {
			Throwable target = ((InvocationTargetException) e).getTargetException();
			if (target instanceof RuntimeException) {
				return (RuntimeException) target;
			}
			return new GenericException("Invocation Target Exception.", target);
		}
		else if (e instanceof RuntimeException) {
			return (RuntimeException) e;
		}
		return new GenericException("Unexpected Checked Exception.", e);
	}


}
